package com.jishaokang.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by NANA_Final on 2019/6/28.
 */
@Component
public class TokenUtil {


    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    public static final String KEYSTRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public static final int len = KEYSTRING.length();

    public Integer getUserIdByToken(String token){
        if (redisTemplate.opsForValue().get(token) == null) return null;
        String userIdString = redisTemplate.opsForValue().get(token).toString();
        if (userIdString == null || userIdString.length()==0) return null;
        return Integer.parseInt(userIdString);
    }

    public String addToken(int userId){
        Random random = new Random();
        StringBuilder sb = new StringBuilder(new Date().getTime()+"");
        for (int i = 0;i < 50;i++ )
            sb = sb.append(KEYSTRING.charAt(random.nextInt(len)));
        String token = sb.toString();
        String userIdString = String.valueOf(userId);
        redisTemplate.opsForValue().set(token,userIdString,2, TimeUnit.HOURS);
        return token;
    }
    public void removeToken(String token){
        System.out.println(token);
        redisTemplate.delete(token);
    }

}